--Zerobyte SERVER BUILD 101
--NOTES:
--IF CLIENT HAS TROUBLE CONNECTING, MAKE SURE host IS SET TO "*"
--TO RECEIVE FROM FLASH, DATA MUST BE HEADED BY NEWLINE(\n)
--TO SEND TO FLASH, DATA MUST BE TERMINATED WITH ZEROBYTE(\0)

--CHANGELOG:
	--FIRST BUILD

socket = require("socket")

--if client has trouble connecting, repalce 'localhost' with '*'
host = "*"
port = 81
concount = 0
connected = "false"

function startserver(param)
	if param == nil then
		else if param == 1 then
			concount = concount + 1
			assert(startserver())
		end
	end
--CREATE SOCKET OBJECT AND BIND TO LOCALHOST THEN LISTEN FOR INCOMING CONNECTIONS
	print("Binding host " .. host .. " to port " .. port)
	server = assert(socket.bind(host, port))
	print("Listening...")
	c = assert(server:accept())
	discon = server:close()
--IF SOMEONE CONNECTED THEN DO EVERYTHING BELOW
	if c then
		connected = "true"
		server:setoption("keepalive", true)
		print("Connect established.  Begining data stream...")
--SEND TO CLIENT AFTER CONNECT------DELETE IN FINAL BUILD
		c:send("CONNECTED\0")
--START RECEIVING DATA
		l, e = c:receive()
		while not e do
			print(l)
			sock:send("OMGLOL")
		    log = io.open("web/log.txt", "a")
	    	log:write(os.date() .. ":  " .. l  .. "\n")
	    	log:close()
			l, e = c:receive()
		end
		print(e)
--GET PORT STATS AND PRINT
 		r, s, t = c:getstats()
 		print(r, s, t)
	end
	if discon then
---------UNCOMMENT C:CLOSE FOR TESTING----------
		c:close()
--		assert(startserver(1))
	end
end

startserver()

--[[SHORTER VERSION, WORK ON AFTER FINISHED PRODUCT

socket = require'socket'
host = "localhost"
port = 5555

function handler(skt)
	dataout = "connected"
	skt:send(dataout)
	datain, eol = skt:receive(pattern)
	while not eol do
		print(datain)
		datain, eol = skt:receive(pattern)
	end
	print(eol)
end

skt = assert(socket.bind(host, port))
reading = {skt}

while true do
  input = socket.select(reading)
  server = assert(skt:accept())
  handler(server)
  return
end

--]]